import {
  IntegrityError,
  isPlayServicesAvailable,
  prepareIntegrityToken,
  requestIntegrityToken,
} from '@pagopa/io-react-native-integrity';

import { GOOGLE_CLOUD_PROJECT_ID } from '@/constants';

export async function getPlayServiceToken() {
  try {
    const isServiceAvailable = await isPlayServicesAvailable();
    if (isServiceAvailable) {
      // Proceed with the following steps
      console.log('start======================');
      console.log('服务开启了');
      console.log('end========================');

      return prepare();
    } else {
      console.log('服务不行, 要检查后台配置');
      // Return an error message
      return '';
    }
  } catch (e) {
    const error = e as IntegrityError;
    console.log(JSON.stringify(error));
    return '';
  }
}

async function getToken() {
  try {
    const token = await requestIntegrityToken();
    return token;
  } catch (e) {
    console.log('我没拿到token了，错误如下');
    const error = e as IntegrityError;
    console.log(JSON.stringify(error));
    return '';
  }
}

async function prepare() {
  try {
    // 这里的554078695577值，就是上面项目关联时，项目的number值，去谷歌后台找
    await prepareIntegrityToken(GOOGLE_CLOUD_PROJECT_ID);
    const token = await getToken();
    return token;
  } catch (e) {
    const error = e as IntegrityError;
    console.log('项目number填错了，请检查配置');
    console.log(JSON.stringify(error));
    return '';
  }
}
